﻿<script setup lang="ts" name="Export">
import useScrollPosition from '@/hooks/scrollPosition'
import { storeToRefs } from 'pinia'
import { useSystemConfigStore } from '@/store/storage/systemConfigStore'
import { jsonToSheetXlsx } from '@/components/Excel/Export2Excel'
import { getListData } from '@/api/export2Excel'
import { warnMessage } from '@/utils/message'
const route = useRoute()

const systemConfigStore = useSystemConfigStore()
const { systemConfig } = storeToRefs(systemConfigStore)

// 滚动行为
useScrollPosition(route)

const pageIndex = ref(1)
const pageSize = ref(20)
const listData: any = reactive({
  data: [],
  total: 0
})

const getInitData = () => {
  getListData({ pageIndex: pageIndex.value, pageSize: pageSize.value }, { config: { showLoading: false, mockEnable: true } }).then((res: any) => {
    if (res.data && res.data.length > 0) {
      setTimeout(() => {
        listData.data = []
        listData.data.push(...res.data)
        listData.total = res.total
      }, 2000)
    }
  })
}
onMounted(() => {
  getInitData()
})

const handleSizeChange = (val) => {
  pageSize.value = val
  pageIndex.value = 1
  getInitData()
}
const handleCurrentChange = (val) => {
  pageIndex.value = val
  getInitData()
}

const defaultHeader = () => {
  console.log(listData.data)
  jsonToSheetXlsx({ data: listData.data, filename: '使用key做默认头部.xlsx' })
}
const customHeader = () => {
  jsonToSheetXlsx({
    data: listData.data,
    header: {
      id: 'ID',
      title: '标题',
      description: '描述',
      date: '发布日期',
      like: '评论',
      author: '作者'
    },
    filename: '自定义头部.xlsx',
    json2sheetOpts: {
      // 指定顺序
      header: ['id', 'title', 'description', 'author', 'like', 'date']
    }
  })
}

const xTable = ref(null)

const selectAllChangeEvent = ({ checked }) => {
  const $table = xTable.value
  const records = $table.getSelectionRows()
  console.log(checked ? '所有勾选事件' : '所有取消事件', records)
}

const selectChangeEvent = ({ checked }) => {
  const $table = xTable.value
  const records = $table.getSelectionRows()
  console.log(checked ? '勾选事件' : '取消事件', records)
}

const getSelectEvent = () => {
  const $table = xTable.value
  const selectRecords = $table.getSelectionRows()
  return selectRecords
}

const exportSelected = () => {
  const selectedData = getSelectEvent()
  if (selectedData.length === 0) {
    warnMessage('请先选择要导出的数据')
    return false
  }
  jsonToSheetXlsx({
    data: getSelectEvent(),
    header: {
      id: 'ID',
      title: '标题',
      description: '描述',
      date: '发布日期',
      like: '评论',
      author: '作者'
    },
    filename: '导出选中.xlsx',
    json2sheetOpts: {
      // 指定顺序
      header: ['id', 'title', 'description', 'author', 'like', 'date']
    }
  })
}

const exportAllData = () => {
  const selectedData = []
  getListData({ pageIndex: 1, pageSize: listData.total }, { config: { showLoading: false, mockEnable: true } }).then((res: any) => {
    if (res.data && res.data.length > 0) {
      selectedData.push(...res.data)
      jsonToSheetXlsx({
        data: selectedData,
        header: {
          id: 'ID',
          title: '标题',
          description: '描述',
          date: '发布日期',
          like: '评论',
          author: '作者'
        },
        filename: '全量导出.xlsx',
        json2sheetOpts: {
          // 指定顺序
          header: ['id', 'title', 'description', 'author', 'like', 'date']
        }
      })
    }
  })
}

const hasSelected = ref(false)
const exportModalRef = ref(null)
const openModal = () => {
  const exportModalRefDom = unref(exportModalRef)
  if (!exportModalRefDom) return
  if (getSelectEvent().length > 0) {
    hasSelected.value = true
  } else {
    hasSelected.value = false
  }
  exportModalRefDom.handleOpenDialog()
}

const fieldList = ref([
  { key: 'id', value: 'ID' },
  { key: 'title', value: '标题' },
  { key: 'description', value: '描述' },
  { key: 'date', value: '发布日期' },
  { key: 'like', value: '评论' },
  { key: 'author', value: '作者' }
])

// 高级导出
const customExport = (obj) => {
  const filename = obj.filename
  const customData = []
  let header = null
  const bookType = obj.fileType
  const headerSort = obj.sort
  if (obj.headerType === 'custom') {
    header = obj.header
  }
  if (obj.dataScope === 1) {
    listData.data.forEach((item) => {
      const itemObj = {}
      headerSort.forEach((current) => {
        itemObj[current] = item[current]
      })
      customData.push(itemObj)
    })
    jsonToSheetXlsx({
      data: customData,
      header: header,
      filename: filename,
      json2sheetOpts: {
        // 指定顺序
        header: headerSort
      },
      write2excelOpts: {
        bookType
      }
    })
  } else if (obj.dataScope === 2) {
    getSelectEvent().forEach((item) => {
      const itemObj = {}
      headerSort.forEach((current) => {
        itemObj[current] = item[current]
      })
      customData.push(itemObj)
    })
    jsonToSheetXlsx({
      data: customData,
      header: header,
      filename: filename,
      json2sheetOpts: {
        // 指定顺序
        header: headerSort
      },
      write2excelOpts: {
        bookType
      }
    })
  } else {
    getListData({ pageIndex: 1, pageSize: listData.total }, { config: { showLoading: false, mockEnable: true } }).then((res: any) => {
      if (res.data && res.data.length > 0) {
        res.data.forEach((item) => {
          const itemObj = {}
          headerSort.forEach((current) => {
            itemObj[current] = item[current]
          })
          customData.push(itemObj)
        })
        jsonToSheetXlsx({
          data: customData,
          header: header,
          filename: filename,
          json2sheetOpts: {
            // 指定顺序
            header: headerSort
          },
          write2excelOpts: {
            bookType
          }
        })
      }
    })
  }
}
</script>

<template>
  <el-space :size="systemConfig.space" fill direction="vertical">
    <el-card shadow="never" class="no-border no-radius">
      <template #header>
        <div class="card-header">
          <span>Excel导出功能</span>
        </div>
      </template>
      <div class="button-list">
        <el-button @click="defaultHeader">导出当前页（默认头部）</el-button>
        <el-button @click="customHeader">导出当前页（自定义头部）</el-button>
        <el-button @click="exportSelected">导出选中</el-button>
        <el-button @click="exportAllData">全量导出后台数据</el-button>
        <el-button @click="openModal">高级导出</el-button>
      </div>
      <el-table ref="xTable" :data="listData.data" border stripe style="width: 100%" @select-all="selectAllChangeEvent" @selection-change="selectChangeEvent">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="50" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="date" label="发布日期" />
        <el-table-column prop="like" label="评论" />
        <el-table-column prop="author" label="作者" />
      </el-table>
      <el-pagination
        v-if="listData.total > 0"
        v-model:currentPage="pageIndex"
        v-model:page-size="pageSize"
        :page-sizes="[20, 40, 100, 200]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="listData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
      <ExportModal ref="exportModalRef" :fieldList="fieldList" :hasSelected="hasSelected" @success="customExport"></ExportModal>
    </el-card>
  </el-space>
</template>

<style scoped lang="scss">
.el-space {
  width: 100%;
  padding: var(--el-space) var(--el-space) 0;
}

.no-border {
  border: none;
}

.no-radius {
  border-radius: 0;
}

.el-card {
  display: flex;
  flex-direction: column;

  :deep(.el-card__header) {
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;

    }
  }

  :deep(.el-card__body) {
    flex: 1;
  }

  .button-list {
    width: 100%;
    margin-bottom: 20px;
  }
}

.el-pagination {
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
